package access_clock;

import bean.Fingerprint_template;
import bean.Fingerprint_templates;
import bean.System_contorl;
import bean.System_logs;

import com.sun.jna.Memory;
import com.sun.jna.Pointer;

import equipment.finger.Finger_tool.CLibrary;
import equipment.finger.Finger_tool.ZKFCLibrary;

public class Access_thread {
	
	public static int capture(int devHandle, byte[] imageBuffer,
			int imageBufferSize) throws InterruptedException{
		
			int ret = CLibrary.INSTANCE.sensorCapture(devHandle, imageBuffer,imageBufferSize);
			/*if (ret > 0) {
				System.out.println("采集到一个指纹!");
			}*/
			return ret;
	}
	
	public static void run(int sensoropen){
		/*
		 * 指纹对比
		 */
	    	int width = CLibrary.INSTANCE.sensorGetParameter(sensoropen, 1);
	    	int height = CLibrary.INSTANCE.sensorGetParameter(sensoropen, 2);
	    	int imgbuffer = CLibrary.INSTANCE.sensorGetParameter(sensoropen, 106);
			
	    	Pointer pSize = new Memory((long)44);
			pSize.setShort(0, (short) width);
			pSize.setShort(2, (short) height);
			pSize.setShort(40, (short) width);
			pSize.setShort(42, (short) height);
	    	int bioinit = ZKFCLibrary.zkf.BIOKEY_INIT(0, pSize, null, null, 0);
	    	if(bioinit == 0){
	    		System.out.println("算法初始化失败");
	    	}
			
	    	
	    	int Fingerprint_migration = ZKFCLibrary.zkf.BIOKEY_SET_PARAMETER(bioinit, 4 , 180);
	    	if(Fingerprint_migration == 0){
	    		System.out.println("指纹偏移角设置失败!");
	    	}
	    	
	    	byte[] imageBuffer = new byte[imgbuffer];
	    	while(System_contorl.getAccess_control() == 1){
	    		try {
	    			int cap = capture(sensoropen, imageBuffer, imgbuffer);
					if(cap>0){
						//System.out.println("采集到一个指纹");
						byte[] template = new byte[2048];
						int act = ZKFCLibrary.zkf.BIOKEY_EXTRACT(bioinit, imageBuffer, template, 1);
						if(act>0){
							int mark = 0;
							for(Fingerprint_template fingerprint_template : Fingerprint_templates.getFingerprint_templates_DB()){
								int re = ZKFCLibrary.zkf.BIOKEY_VERIFY(bioinit,template,fingerprint_template.getFingerprint_template());
								if(re>0){
									System_logs.system_log(0, fingerprint_template.getFingerprint_template_id(), 1);
									//System.out.println("1:1对比分值为"+re);
									mark = 1;
									break;
								}
							}
							if(mark == 0){
								System_logs.system_log(0, null, 0);
							}
								
						}
						
					}else if(cap == 0){
						//System.out.println("没有采集到图像!");
					}else if(cap == -2){
						System.out.println("sensoropen或imageBuffer为空!");
					}else if(cap == -3){
						System.out.println("申请的空间小于采集到的图像大小，空间不足!");
					}
					Thread.sleep(30);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
	    	
	    		CLibrary.INSTANCE.sensorFree();
		    	ZKFCLibrary.zkf.BIOKEY_CLOSE(bioinit);
	}
}
